package activities;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import orm.Person;
import orm.PersonDbHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableRow;

import com.example.intellifit.R;

public class Account extends Activity {

	private Button saveUserInformationBtn, deletAccountBtn, pickDateBtn;
	private EditText idTxt, titleTxt, fNameTxt, lNameTxt, nationTxt, genderTxt, 
			android_idTxt;
	private static String ANDROID_ID = Build.SERIAL;
    private int mYear, mMonth, mDay;
    static final int DATE_DIALOG_ID = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
     setContentView(R.layout.account);
		init();
	}

	/*
	 * Inits the TextEdit fields with user information Adds the buttons
	 */
	public void init() {
		// if device has no id or for the simulator
		if (ANDROID_ID == null) {
			ANDROID_ID = "empty";
		}

		idTxt = (EditText) findViewById(R.id.idText);
		TableRow tb = (TableRow)findViewById(R.id.tableRow0);
		tb.setVisibility(View.INVISIBLE);
		titleTxt = (EditText) findViewById(R.id.titleText);
		fNameTxt = (EditText) findViewById(R.id.fnameText);
		lNameTxt = (EditText) findViewById(R.id.lnameText);
		nationTxt = (EditText) findViewById(R.id.nationText);
		genderTxt = (EditText) findViewById(R.id.genderText);
		android_idTxt = (EditText) findViewById(R.id.android_idText);
        // capture our View elements
		pickDateBtn = (Button) findViewById(R.id.pickDate);
		

		// Check if it exists a user for this device
		Person p = PersonDbHelper.getPersonByAndroi_ID(this, ANDROID_ID);
		if (p == null) {
			p = addDummyUser();
		}

		render(p);

		deletAccountBtn = (Button) findViewById(R.id.deletAccountBtn);
		deletAccountBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d("Delete Account: ", "Deleting ..");
				int success = deleteAccount();
				init();

			}
		});

		saveUserInformationBtn = (Button) findViewById(R.id.saveAccountBtn);
		saveUserInformationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d("SAVE: ", "Saving ..");
				save();

			}
		});
		
		makeDatePicker();

	}

	/*
	 * Updates the person with the current id
	 */
	public void save() {

		Date date = new Date();
		alert("Saving?", "Are you sure?");

			try {
				SimpleDateFormat iso8601Format = new SimpleDateFormat("dd-MM-yyyy");
				date = iso8601Format.parse(pickDateBtn.getText().toString());
			} catch (java.text.ParseException e) {
				date = new Date();
				e.printStackTrace();
			}

		Person p = new Person(Integer.valueOf(idTxt.getText().toString()),
				titleTxt.getText().toString(),
				fNameTxt.getText().toString(), 
				lNameTxt.getText().toString(),
				nationTxt.getText().toString(),
				genderTxt.getText().toString(), 
				date,
				android_idTxt.getText().toString());

		PersonDbHelper.savePerson(this, p);
		

	}
	
	/*
	 * Renders the person to the Android view
	 */
	private void render(Person p) {

		if (p != null) {
			if (p.getFName() != null) {
				idTxt.setText("" + p.getID());
			}
			if (p.getTitle() != null) {
				titleTxt.setText("" + p.getTitle());
			}
			if (p.getFName() != null) {
				fNameTxt.setText(p.getFName());
			}
			if (p.getLName() != null) {
				lNameTxt.setText(p.getLName());
			}
			if (p.getNation() != null) {
				nationTxt.setText("" + p.getNation());
			}
			if (p.getDateOfBirth() != null) {
				pickDateBtn.setText(p.getDateOfBirth().toString());
			}
			if (p.getGender() != null) {
				genderTxt.setText(p.getGender());
			}
		}
		android_idTxt.setText(ANDROID_ID);
	}

	/*
	 * Creates a empty user with the current Android ID
	 */
	public Person addDummyUser() {

		long id = PersonDbHelper.addPerson(this, new Person(-1, "-", "-", "-", "-", "-", new Date(),
				ANDROID_ID));
		return PersonDbHelper.getPersonByID(this, (int) id);

	}
	
	/**
	 * Deletes the current account
	 * @return the number of rows affected, 0 or -1 if no success
	 */
	public int deleteAccount() {
		if(Integer.valueOf(idTxt.getText().toString()) != null){
			return PersonDbHelper.delete(this, Integer.valueOf(idTxt.getText().toString()));
		}
		return -1;

	}

	/*
	 * alert function for the account
	 * 
	 */
	final boolean flag = false;
	public void alert(String title, String msg) {

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

		// set title
		alertDialogBuilder.setTitle(title);

		// set dialog message
		alertDialogBuilder
				.setMessage(msg)
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
								
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();
	}
	
	
	private void makeDatePicker(){
		/*   Date   */


        // add a click listener to the button
		pickDateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	// use deprecated method to achieve backward compatibility
                showDialog(DATE_DIALOG_ID);
            }
        });

        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();
	}
	
	/* Date */
    // updates the date in the TextView
    private void updateDisplay() {
    	pickDateBtn.setText(getString(R.string.strSelectedDate,
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mDay).append("-")
                    .append(mMonth + 1).append("-")
                    .append(mYear).append(" ")));
    }
    
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };
            
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}
	
	/*Date*/

}
